package cn.glutnn.subject.domain.handler.subject;

import cn.glutnn.subject.common.enums.IsDeletedFlagEnum;
import cn.glutnn.subject.common.enums.SubjectInfoTypeEnum;
import cn.glutnn.subject.domain.convert.SubjectMultiConverter;
import cn.glutnn.subject.domain.enyity.SubjectAnswerBO;
import cn.glutnn.subject.domain.enyity.SubjectInfoBO;
import cn.glutnn.subject.domain.enyity.SubjectOptionBO;
import cn.glutnn.subject.infra.basic.entity.SubjectMultiple;
import cn.glutnn.subject.infra.basic.service.SubjectMultipleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

/**
 * Author:   msh
 * Date:     2024/11/28 下午2:51
 * Description:
 */

@Component
public class MultiTypeHandler implements SubjectTypeHandler {

    @Resource
    private SubjectMultipleService subjectMultipleService;

    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.MULTIPLE;
    }

    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        LinkedList<SubjectMultiple> subjectMultiples = new LinkedList<>();
        subjectInfoBO.getOptionList().forEach(subjectAnswerBO -> {
            SubjectMultiple subjectMultiple = SubjectMultiConverter.INSTANCE.convertBoToEntity(subjectAnswerBO);
            subjectMultiple.setSubjectId(subjectInfoBO.getId());
            subjectMultiple.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            subjectMultiples.add(subjectMultiple);
        });
        subjectMultipleService.saveBatch(subjectMultiples);
    }

    @Override
    public SubjectOptionBO query(Long subjectId) {
        LambdaQueryWrapper<SubjectMultiple> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SubjectMultiple::getSubjectId, subjectId);
        List<SubjectMultiple> subjectMultiples = subjectMultipleService.list(wrapper);
        SubjectOptionBO optionBO = new SubjectOptionBO();
        LinkedList<SubjectAnswerBO> answerList = new LinkedList<>();
        subjectMultiples.forEach(subjectMultiple -> {
            SubjectAnswerBO answerBO = new SubjectAnswerBO();
            answerBO.setOptionType(subjectMultiple.getOptionType());
            answerBO.setOptionContent(subjectMultiple.getOptionContent());
            answerBO.setIsCorrect(subjectMultiple.getIsCorrect());
            answerList.add(answerBO);
        });
        optionBO.setOptionList(answerList);
        return optionBO;
    }
}
